<template>
  <div class="app-container">
    <div class="filter-container query">
      <el-form :model="listQuery" label-position="right" label-width="120px">
        <el-row :gutter="10">
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="企业名称" prop="companyId">
              <el-select v-model="listQuery.companyId" clearable filterable placeholder="请选择企业">
                <el-option
                  v-for="item in companyOptions"
                  :key="item.companyId"
                  :label="item.companyName"
                  :value="item.companyId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="站点名称" prop="stationId">
              <el-select v-model="listQuery.stationId" clearable filterable placeholder="请选择站点">
                <el-option
                  v-for="item in stationOptions"
                  :key="item.stationId"
                  :label="item.stationName"
                  :value="item.stationId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="二维码编号" prop="qrcodeNo">
              <el-input v-model="listQuery.qrcodeNo" @keyup.enter.native="handleFilter" />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="二维码名称" prop="qrcodeName">
              <el-input v-model="listQuery.qrcodeName" @keyup.enter.native="handleFilter" />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="范围类型" prop="scopeType">
              <el-select v-model="listQuery.scopeType" clearable class="filter-item">
                <el-option v-for="item in scopeTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="二维码类型" prop="qrcodeType">
              <el-select v-model="listQuery.qrcodeType" clearable class="filter-item">
                <el-option v-for="item in qrcodeTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="启用标记" prop="enableFlag">
              <el-select v-model="listQuery.enableFlag" clearable class="filter-item">
                <el-option v-for="item in enableFlagOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleFilter">
            搜索
          </el-button>
          <el-button type="info" icon="el-icon-refresh" size="small" @click="handleReset">
            重置
          </el-button>
        </el-row>
        <el-row :gutter="10">
          <el-button type="success" icon="el-icon-circle-plus-outline" :loading="createDownloading" size="small" @click="handleCreate(1)">
            生成二维码图片
          </el-button>
          <el-button type="success" icon="el-icon-circle-plus-outline" :loading="createDownloading" size="small" @click="handleCreate(2)">
            生成二维码Excel
          </el-button>
          <el-button v-show=" multipleSelection && multipleSelection.length >0" :loading="zipFileDownloading" type="danger" icon="el-icon-download" size="small" @click="handleDownloadIds(1)">
            下载二维码图片
          </el-button>
          <el-button v-show=" multipleSelection && multipleSelection.length >0" :loading="zipFileDownloading" type="danger" icon="el-icon-download" size="small" @click="handleDownloadIds(2)">
            下载二维码Excel
          </el-button>
        </el-row>
      </el-form>
    </div>

    <el-table
      :loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;height: 100%;"
      size="small"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="{row}">
          <el-button size="mini" type="primary" @click="handleView(row)">
            预览
          </el-button>
          <el-button size="mini" type="success" @click="handleDownload(row)">
            下载
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="范围类型" prop="scopeType" :formatter="formatter" width="80" header-align="center" align="center" />
      <el-table-column label="企业名称" prop="companyName" width="180" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.companyName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="站点名称" prop="stationName" width="180" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.stationName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="二维码编号" prop="qrcodeNo" width="150" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.qrcodeNo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="二维码名称" prop="qrcodeName" width="200" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.qrcodeName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="二维码类型" prop="qrcodeType" :formatter="formatter" width="100" header-align="center" align="center" />
      <el-table-column label="启用标记" prop="enableFlag" :formatter="formatter" width="100" header-align="center" align="center" />
      <el-table-column label="开始时间" prop="startTime" width="100" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.startTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" prop="endTime" width="100" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.endTime }}</span>
        </template>
      </el-table-column><el-table-column label="创建时间" prop="createAt" width="180" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.createAt }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageNoSize" size="small" @pagination="getList" />

    <el-dialog :title="dialogTitleMap[dialogStatus]" :visible.sync="dialogFormVisible" top="10vh" width="520px" :close-on-click-modal="false" :close-on-press-escape="false" center>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px" class="form-center">
        <el-form-item label="范围类型" prop="scopeType">
          <el-select v-model="temp.scopeType" clearable placeholder="请选择二维码范围">
            <el-option v-for="item in scopeTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="temp.scopeType==='2' || temp.scopeType==='3'" label="企业名称" prop="companyId">
          <el-select v-model="temp.companyId" clearable filterable placeholder="请选择企业">
            <el-option
              v-for="item in companyOptions"
              :key="item.companyId"
              :label="item.companyName"
              :value="item.companyId"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="temp.scopeType==='3'" label="站点名称" prop="stationId">
          <el-select v-model="temp.stationId" clearable multiple filterable placeholder="请选择站点">
            <el-option
              v-for="item in stationOptions"
              :key="item.stationId"
              :label="item.stationName"
              :value="item.stationId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="二维码类型" prop="qrcodeType">
          <el-select v-model="temp.qrcodeType" placeholder="二维码类型" clearable>
            <el-option v-for="item in qrcodeTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="生成数量" prop="num">
          <el-input-number v-model="temp.num" :min="0" :max="99999999" :precision="0" :controls="false" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" :loading="createDownloading" @click="createData(dialogStatus=='create1'?1:2)">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="图片预览" :visible.sync="imageDialogVisible" top="3vh" width="520px" :close-on-click-modal="false" :close-on-press-escape="false" center>
      <el-form :rules="rules" :model="imageData" label-position="right" label-width="120px" class="form-center">
        <el-row class="text-center">
          <span style="font-weight:bold;font-size:25px">{{ imageData.title }}</span>
        </el-row>
        <el-row class="text-center">
          <el-image
            :src="imageData.image"
            :preview-src-list="[imageData.image]"
          />
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="imageDialogVisible = false">
          关闭
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getSmskQrcodeList, view, createQrcode, downloadQrcode, downloadExcel, createQrcodeExcel } from '@/api/smsk/qrcode'
import { selectCompanyList } from '@/api/smsk/company'
import { selectStationList } from '@/api/smsk/station'
import Pagination from '@/components/Pagination'
import { setOptionData, valueFormate } from '@/utils/dict'
import { saveRespExcel } from '@/utils'

export default {
  name: 'SmskQrcode',
  components: { Pagination },
  data() {
    const companyIdValidate = (rule, value, callback) => {
      if ((this.temp.scopeType === '2' || this.temp.scopeType === '3') && (value == null || value.length < 1)) {
        callback(new Error('企业名称不能为空'))
      } else {
        callback()
      }
    }
    return {
      enableFlagOptions: [],
      companyOptions: [],
      stationOptions: [],
      scopeTypeOptions: [],
      qrcodeTypeOptions: [],
      list: [],
      total: 0,
      listLoading: false,
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        companyId: null,
        stationId: null,
        qrcodeNo: '',
        qrcodeName: '',
        qrcodeType: '',
        scopeType: '',
        enableFlag: '',
        sortField: undefined,
        sortOrder: undefined
      },
      createDownloading: false,
      zipFileDownloading: false,
      dialogFormVisible: false,
      imageDialogVisible: false,
      dialogStatus: '',
      multipleSelection: null,
      imageData: {
        title: '',
        image: ''
      },
      dialogTitleMap: {
        create1: '生成二维码',
        create2: '生成二维码表格'
      },
      temp: {
        scopeType: '',
        companyId: null,
        stationId: [],
        qrcodeType: '',
        num: null
      },
      rules: {
        scopeType: [{ required: true, message: '范围类型不能为空', trigger: 'change' }],
        companyId: [{ validator: companyIdValidate, message: '企业名称不能为空', trigger: 'change' }],
        qrcodeType: [{ required: true, message: '二维码类型不能为空', trigger: 'change' }],
        num: [{ required: true, message: '生成数量不能为空', trigger: 'change' }]
      }
    }
  },
  watch: {
    'listQuery.companyId': function(newVal, oldVal) {
      console.log(newVal)
      if (newVal) {
        this.getStationList(newVal)
      }
    },
    'temp.companyId': function(newVal, oldVal) {
      console.log(newVal)
      if (newVal) {
        this.getStationList(newVal)
      }
    }
  },
  created() {
    this.initDictInfos()
    // 加载下拉数据
    const optionsMap = new Map()
    optionsMap.set('SMSK_QRCODE_SCOPE', this.scopeTypeOptions)
    optionsMap.set('SMSK_QRCODE_TYPE', this.qrcodeTypeOptions)
    optionsMap.set('YES_OR_NO', this.enableFlagOptions)
    setOptionData(optionsMap)
    this.getList()
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    formatter(row, column, cellValue, index) {
      return valueFormate(this, column.property, cellValue)
    },
    initDictInfos() { // 初始化数据字典
      // 加载下拉数据
      selectCompanyList().then(res => {
        this.companyOptions = res.data
      })
    },
    getStationList(companyId) {
      selectStationList(companyId).then(res => {
        this.stationOptions = res.data
      })
    },
    getList() {
      this.listLoading = true
      getSmskQrcodeList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      }, response => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleReset() {
      this.listQuery = {
        companyId: null,
        stationId: null,
        qrcodeNo: '',
        qrcodeName: '',
        qrcodeType: '',
        enableFlag: ''
      }
    },
    handleView(row) {
      this.imageData.title = row.name
      view(row.id).then(response => {
        this.imageData.image = 'data:image/png;base64,' + response.data
      })
      this.imageDialogVisible = true
    },
    resetTemp() {
      this.temp = {
        companyId: null,
        stationId: [],
        qrcodeType: '',
        num: null
      }
    },
    handleCreate(flag) {
      this.resetTemp()
      this.dialogStatus = 'create' + flag
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDownload(row) {
      view(row.id).then(response => {
        this.downloadQrCode(response.data)
        this.$message({
          message: '二维码下载成功',
          type: 'success'
        })
      })
    },
    createData(flag) {
      if (flag === 1) {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.createDownloading = true
            createQrcode(this.temp).then(response => {
              this.$message({
                message: '二维码创建成功',
                type: 'success'
              })
              saveRespExcel(response)
              this.createDownloading = false
              this.dialogFormVisible = false
            }, response => {
              this.createDownloading = false
            })
          }
        })
      } else {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.createDownloading = true
            createQrcodeExcel(this.temp).then(response => {
              this.$message({
                message: '二维码创建成功',
                type: 'success'
              })
              saveRespExcel(response)
              this.createDownloading = false
              this.dialogFormVisible = false
            }, response => {
              this.createDownloading = false
            })
          }
        })
      }
    },
    sortChange(data) {
      const { prop, order } = data
      this.sortByField(prop, order)
    },
    sortByField(prop, order) {
      if (order === 'ascending') {
        this.listQuery.sortField = prop
        this.listQuery.sortOrder = 'asc'
      } else if (order === 'descending') {
        this.listQuery.sortField = prop
        this.listQuery.sortOrder = 'desc'
      } else {
        this.listQuery.sortField = undefined
        this.listQuery.sortOrder = undefined
      }
      this.handleFilter()
    },
    handleDownloadIds(flag) {
      this.zipFileDownloading = true
      const data = { ids: [] }
      Object.keys(this.multipleSelection).forEach(index => {
        data.ids.push(this.multipleSelection[index].id)
      })
      if (data.ids.length === 0) {
        return
      }
      if (flag === 1) {
        downloadQrcode(data).then(response => {
          this.$message({
            message: '二维码下载成功',
            type: 'success'
          })
          saveRespExcel(response)
          this.zipFileDownloading = false
        }, response => {
          this.zipFileDownloading = false
        })
      } else {
        downloadExcel(data).then(response => {
          this.$message({
            message: '二维码Excel下载成功',
            type: 'success'
          })
          saveRespExcel(response)
          this.zipFileDownloading = false
        }, response => {
          this.zipFileDownloading = false
        })
      }
    },
    downloadQrCode(image) {
      const imgUrl = 'data:image/jpg;base64,' + image
      // 如果浏览器支持msSaveOrOpenBlob方法（也就是使用IE浏览器的时候），那么调用该方法去下载图片
      if (window.navigator.msSaveOrOpenBlob) {
        const bstr = atob(imgUrl.split(',')[1])
        let n = bstr.length
        const u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        const blob = new Blob([u8arr])
        window.navigator.msSaveOrOpenBlob(blob, 'qrcode.jpg')
      } else {
        // 这里就按照chrome等新版浏览器来处理
        const a = document.createElement('a')
        a.href = imgUrl
        a.setAttribute('download', 'qrcode.jpg')
        a.click()
      }
    }
  }
}
</script>
